<template>
  <div class="reminder-template-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>提醒模板管理</span>
          <el-button type="primary" @click="showAddTemplateDialog">新增模板</el-button>
        </div>
      </template>
      
      <!-- 搜索 -->
      <div class="search-filter">
        <el-input v-model="searchQuery" placeholder="搜索模板名称" prefix-icon="Search" style="width: 300px; margin-right: 15px;"></el-input>
        <el-select v-model="selectedType" placeholder="选择模板类型" style="width: 200px; margin-right: 15px;">
          <el-option label="全部" value=""></el-option>
          <el-option label="提肛运动" value="exercise"></el-option>
          <el-option label="鼻炎护理" value="rhinitis"></el-option>
          <el-option label="饮食提醒" value="diet"></el-option>
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      
      <!-- 模板表格 -->
      <el-table :data="templatesData" style="width: 100%">
        <el-table-column prop="id" label="模板ID" width="80"></el-table-column>
        <el-table-column prop="name" label="模板名称" width="180"></el-table-column>
        <el-table-column prop="type" label="模板类型" width="120">
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.type)">
              {{ getTypeName(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="提醒标题" width="200"></el-table-column>
        <el-table-column prop="content" label="提醒内容">
          <template #default="scope">
            <div class="content-preview" :title="scope.row.content">
              {{ scope.row.content.length > 50 ? scope.row.content.substring(0, 50) + '...' : scope.row.content }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="frequency" label="默认频率" width="120">
          <template #default="scope">
            {{ getFrequencyText(scope.row.frequency) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
              {{ scope.row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button type="primary" size="small" @click="showEditTemplateDialog(scope.row)">编辑</el-button>
            <el-button :type="scope.row.status === 'active' ? 'danger' : 'success'" size="small" @click="handleToggleStatus(scope.row)">
              {{ scope.row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 新增/编辑模板对话框 -->
    <el-dialog v-model="templateDialogVisible" :title="dialogTitle" width="700px">
      <el-form :model="templateForm" :rules="templateRules" ref="templateFormRef" label-width="120px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="templateForm.name" placeholder="请输入模板名称"></el-input>
        </el-form-item>
        <el-form-item label="模板类型" prop="type">
          <el-select v-model="templateForm.type" placeholder="请选择模板类型">
            <el-option label="提肛运动" value="exercise"></el-option>
            <el-option label="鼻炎护理" value="rhinitis"></el-option>
            <el-option label="饮食提醒" value="diet"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="提醒标题" prop="title">
          <el-input v-model="templateForm.title" placeholder="请输入提醒标题"></el-input>
        </el-form-item>
        <el-form-item label="提醒内容" prop="content">
          <el-input v-model="templateForm.content" type="textarea" :rows="4" placeholder="请输入提醒内容"></el-input>
        </el-form-item>
        <el-form-item label="默认频率" prop="frequency">
          <el-select v-model="templateForm.frequency" placeholder="请选择默认频率">
            <el-option label="每天" value="daily"></el-option>
            <el-option label="每周" value="weekly"></el-option>
            <el-option label="每月" value="monthly"></el-option>
            <el-option label="自定义" value="custom"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="templateForm.frequency === 'weekly'" label="每周重复">
          <el-checkbox-group v-model="templateForm.weekdays">
            <el-checkbox label="1">周一</el-checkbox>
            <el-checkbox label="2">周二</el-checkbox>
            <el-checkbox label="3">周三</el-checkbox>
            <el-checkbox label="4">周四</el-checkbox>
            <el-checkbox label="5">周五</el-checkbox>
            <el-checkbox label="6">周六</el-checkbox>
            <el-checkbox label="7">周日</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="默认时间" prop="defaultTime">
          <el-time-picker v-model="templateForm.defaultTime" placeholder="选择时间" value-format="HH:mm"></el-time-picker>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="templateForm.status" active-value="active" inactive-value="inactive"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="templateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveTemplate">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 搜索和筛选条件
const searchQuery = ref('')
const selectedType = ref('')

// 表格数据
const templatesData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 对话框状态
const templateDialogVisible = ref(false)
const editingTemplateId = ref(null)
const templateFormRef = ref()

// 模板表单
const templateForm = reactive({
  name: '',
  type: '',
  title: '',
  content: '',
  frequency: 'daily',
  weekdays: ['1', '2', '3', '4', '5'],
  defaultTime: '09:00',
  status: 'active'
})

// 表单验证规则
const templateRules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 2, max: 50, message: '模板名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择模板类型', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入提醒标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入提醒内容', trigger: 'blur' }
  ],
  frequency: [
    { required: true, message: '请选择默认频率', trigger: 'change' }
  ],
  defaultTime: [
    { required: true, message: '请选择默认时间', trigger: 'change' }
  ]
}

// 对话框标题
const dialogTitle = computed(() => {
  return editingTemplateId.value ? '编辑提醒模板' : '新增提醒模板'
})

// 获取标签类型
const getTagType = (type) => {
  const typeMap = {
    'exercise': 'success',
    'rhinitis': 'warning',
    'diet': 'info',
    'other': 'primary'
  }
  return typeMap[type] || 'primary'
}

// 获取类型名称
const getTypeName = (type) => {
  const typeMap = {
    'exercise': '提肛运动',
    'rhinitis': '鼻炎护理',
    'diet': '饮食提醒',
    'other': '其他'
  }
  return typeMap[type] || type
}

// 获取频率文本
const getFrequencyText = (frequency) => {
  const frequencyMap = {
    'daily': '每天',
    'weekly': '每周',
    'monthly': '每月',
    'custom': '自定义'
  }
  return frequencyMap[frequency] || frequency
}

// 获取模板列表
const fetchTemplates = () => {
  // 实际项目中应该从后端获取数据
  // 这里使用模拟数据
  const mockData = [
    {
      id: 1,
      name: '提肛运动提醒',
      type: 'exercise',
      title: '该做提肛运动了！',
      content: '您好，每天定时进行提肛运动有助于改善盆底肌功能，预防痔疮等疾病。建议每次持续5-10分钟，保持规律锻炼。',
      frequency: 'daily',
      defaultTime: '09:00',
      status: 'active',
      createdAt: '2023-07-01 10:00:00'
    },
    {
      id: 2,
      name: '鼻炎护理提醒',
      type: 'rhinitis',
      title: '鼻炎季节防护提醒',
      content: '当前季节是鼻炎高发期，请注意：1.保持室内空气流通 2.外出佩戴口罩 3.按时使用鼻喷药物 4.避免接触过敏原。',
      frequency: 'daily',
      defaultTime: '08:30',
      status: 'active',
      createdAt: '2023-07-02 11:00:00'
    },
    {
      id: 3,
      name: '健康饮食提醒',
      type: 'diet',
      title: '健康饮食小贴士',
      content: '今日饮食建议：多吃新鲜蔬果，减少盐分摄入，适量补充蛋白质，多喝水。保持均衡饮食对身体健康至关重要。',
      frequency: 'daily',
      defaultTime: '12:00',
      status: 'active',
      createdAt: '2023-07-03 12:00:00'
    }
  ]
  
  // 应用搜索和筛选
  let filteredData = [...mockData]
  if (searchQuery.value) {
    filteredData = filteredData.filter(template => 
      template.name.includes(searchQuery.value)
    )
  }
  if (selectedType.value) {
    filteredData = filteredData.filter(template => template.type === selectedType.value)
  }
  
  total.value = filteredData.length
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  templatesData.value = filteredData.slice(start, end)
}

// 显示新增模板对话框
const showAddTemplateDialog = () => {
  editingTemplateId.value = null
  // 重置表单
  if (templateFormRef.value) {
    templateFormRef.value.resetFields()
  }
  // 重置表单数据
  templateForm.name = ''
  templateForm.type = ''
  templateForm.title = ''
  templateForm.content = ''
  templateForm.frequency = 'daily'
  templateForm.weekdays = ['1', '2', '3', '4', '5']
  templateForm.defaultTime = '09:00'
  templateForm.status = 'active'
  templateDialogVisible.value = true
}

// 显示编辑模板对话框
const showEditTemplateDialog = (template) => {
  editingTemplateId.value = template.id
  templateForm.id = template.id
  templateForm.name = template.name
  templateForm.type = template.type
  templateForm.title = template.title
  templateForm.content = template.content
  templateForm.frequency = template.frequency
  templateForm.weekdays = template.weekdays || ['1', '2', '3', '4', '5']
  templateForm.defaultTime = template.defaultTime
  templateForm.status = template.status
  templateDialogVisible.value = true
}

// 保存模板
const handleSaveTemplate = () => {
  templateFormRef.value.validate((valid) => {
    if (valid) {
      // 实际项目中应该调用API保存数据
      ElMessage.success(editingTemplateId.value ? '模板编辑成功' : '模板新增成功')
      templateDialogVisible.value = false
      fetchTemplates()
    }
  })
}

// 切换模板状态
const handleToggleStatus = (template) => {
  const newStatus = template.status === 'active' ? 'inactive' : 'active'
  // 实际项目中应该调用API更新状态
  ElMessage.success(`模板已${newStatus === 'active' ? '启用' : '禁用'}`)
  fetchTemplates()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchTemplates()
}

// 重置搜索
const resetSearch = () => {
  searchQuery.value = ''
  selectedType.value = ''
  currentPage.value = 1
  fetchTemplates()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchTemplates()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  fetchTemplates()
}

// 初始化数据
fetchTemplates()
</script>

<style scoped>
.reminder-template-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-filter {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.content-preview {
  word-break: break-word;
  color: #606266;
}
</style>